/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.lcm.metadata.common.util;

import com.inspur.edp.lcm.metadata.api.entity.DbConnectionInfo;
import io.iec.edp.caf.commons.dataaccess.DbConfigDataConvertor;
import io.iec.edp.caf.commons.dataaccess.DbType;
import io.iec.edp.caf.commons.dataaccess.GSPDbConfigData;
import io.iec.edp.caf.commons.dataaccess.JDBCConnectionInfo;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbUtil {
    public static void testDBConnection(DbConnectionInfo dbConnectionInfo) {
        JDBCConnectionInfo dbConfigData = getDbConfigData(dbConnectionInfo);
        try {
            DriverManager.getConnection(dbConfigData.getDatabaseURL(), dbConfigData.getUserName(), dbConfigData.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private static JDBCConnectionInfo getDbConfigData(DbConnectionInfo dbConnectionInfo) {
        String source = dbConnectionInfo.getDbServerIP() + ":" + dbConnectionInfo.getDbPort();
        source = dbConnectionInfo.getDbType().equals(DbType.Oracle) ? source + "/" + dbConnectionInfo.getDbName() : source;
        GSPDbConfigData gspDbConfigData = new GSPDbConfigData();
        gspDbConfigData.setDbType(dbConnectionInfo.getDbType());
        gspDbConfigData.setSource(source);
        gspDbConfigData.setCatalog(dbConnectionInfo.getDbName());
        gspDbConfigData.setUserId(dbConnectionInfo.getDbUserName());
        gspDbConfigData.setPassword(dbConnectionInfo.getDbPassword());
        JDBCConnectionInfo dbConfigData = DbConfigDataConvertor.Convert(gspDbConfigData);
        return dbConfigData;
    }
}
